package com.zsk.base64;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;

import org.apache.commons.codec.binary.Base64;

public class ImageBase64Util {

    public static String imageToBase64(String imagePath) {
        int index = imagePath.lastIndexOf(".");
        byte[] bys = null;
        try {
            bys = Files.readAllBytes(new File(imagePath).toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64ImageStr = Base64.encodeBase64String(bys);
        base64ImageStr = "data:image/" + imagePath.substring(index + 1) + ";base64," + base64ImageStr;
        return base64ImageStr;
    }

    public static void main(String[] args) {
        String imagePath =
            "E:\\eclipse-workspace\\springboot-fileupload\\src\\main\\resources\\static\\img\\disconnect.png";

        FileWriter writer;
        try {
            writer = new FileWriter("/image.txt");
            // 清空原文件内容
            writer.write("");
            writer.write(imageToBase64(imagePath));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("/image.txt");
    }
}
